﻿/*
*类名：EventHandlerScan
*归属：QinMing.Weixin.EventHandlerScan命名空间
*用途：处理微信用户发给公众号的扫描带参数二维码事件（已关注的用户扫描的情况），并给予微信用户处理结果通知，通过微信服务器转发给微信用户
*作者：乱世刀疤
*日期：2020.05.02
*/

using System;
using System.Web;
using System.Xml;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using QinMing.Config;
using QinMing.Tools;
using QinMing.Weixin.ReturnContent;

namespace QinMing.Weixin.EventHandlerScan
{
	//事件消息处理：已关注公众号用户扫描带参数二维码
    public class ScanEventDeal :System.Web.UI.Page
    {

		public string DealResult(string weixinXML)
        {
            string content = DealScan(weixinXML);  
            return content;
        }

        public string DealScan(string weixinXML)
        {
            string content1="";
            string strresponse = "";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(weixinXML);
            XmlNodeList list = doc.GetElementsByTagName("xml");
            XmlNode xn = list[0];
            string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText;   //关注用户的加密后openid
            string ToUserName = xn.SelectSingleNode("//ToUserName").InnerText;       //公众微信号原始ID
            string MsgType=xn.SelectSingleNode("//MsgType").InnerText;
            string Event=xn.SelectSingleNode("//Event").InnerText;
			string EventKey = xn.SelectSingleNode("//EventKey").InnerText;
			string Ticket = xn.SelectSingleNode("//Ticket").InnerText;
			string tmpEventKey = EventKey.Substring(EventKey.LastIndexOf("_") + 1);
			
			//老用户扫描带参数二维码事件处理
			strresponse = ScanWithQrCodeOld(FromUserName, ToUserName, EventKey);
			
			//保存扫描带参数二维码事件信息
			SaveEventScan(FromUserName, ToUserName, tmpEventKey, Ticket);
			
            //给管理员发送老用户扫描带参数二维码通知
			QinMing.WeixinTemplateMessage.SendTemplateMessage.SendRemindMsg("管理员openid", "老粉丝扫描带参数二维码" + FromUserName, "http://www.yourweb.com/Weixin/DisplayOneUser.aspx?open_id=" + FromUserName);  
			
			return strresponse;
        }
		
        //根据二维码id进行相应处理。
		public string ScanWithQrCodeOld(string FromUserName, string ToUserName, string EventKey)
        {
            string strresponse = "";
			ReturnMsg rm = new ReturnMsg();

            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
			SqlDataReader dr;
            cmd.Connection = conn;
			
            cmd.CommandText = "select * from weixin_qrcode_ticket where scene_id=" + EventKey + " ";
            dr = cmd.ExecuteReader();
			if(dr.Read())
			{
                if(dr["scan_type"].ToString() == "优惠券")
				{
					strresponse = rm.ReturnTuWen(FromUserName,ToUserName, dr["scan_title"].ToString(), dr["scan_title_sub"].ToString(), dr["scan_image_url"].ToString(), dr["scan_redirect_url"].ToString());
					dr.Close();
					
					//插入海报被扫码的记录
					cmd.CommandText = "insert into weixin_ad_image_read_log (share_qrcode_id,read_open_id,read_time) values (" 
					    + EventKey + ",'" + FromUserName + "',getdate())"; //EventKey对应的是weixin_qrcode_ticket表中的scene_id，二维码分配关系
					cmd.ExecuteScalar();
				}
				else
				{
                     dr.Close();
				}
				
				if (conn.State == ConnectionState.Open)
				{
					conn.Close();
					conn.Dispose();
				}
			}
			
			return strresponse;
		}
		
		//保存扫描带参数二维码事件信息。
        public void SaveEventScan(string FromUserName, string ToUserName,string EventKey, string Ticket)
        {
            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "insert into weixin_recv_event (msg_type,event_type,open_id,gh_id,recv_time,event_key,ticket) "
			    + "values ('event','SCAN','" + FromUserName + "','" + ToUserName + "',getdate(),'" + EventKey + "','" + Ticket + "') ";
            QinMingTools.WriteLog("sql语句：", cmd.CommandText);
			cmd.ExecuteScalar();
      
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }
    }
}